package com.zyj.exoplayerdemo

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource
import com.google.android.exoplayer2.upstream.RawResourceDataSource
import com.google.android.exoplayer2.upstream.cache.CacheDataSource
import com.zyj.exoplayerdemo.databinding.ActivityPlayMp4Binding

class PlayMp4Activity : AppCompatActivity() {

    private lateinit var binding: ActivityPlayMp4Binding

    private var mExoPlayer: ExoPlayer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityPlayMp4Binding.inflate(layoutInflater)
        setContentView(binding.root)

        initMp4()

        binding.playView.player = mExoPlayer
        mExoPlayer?.playWhenReady = true

        binding.loadLocal.setOnClickListener {
            //加载本地资源
            val uri = RawResourceDataSource.buildRawResourceUri(R.raw.jinjimp4)
            val mediaItem: MediaItem = MediaItem.fromUri(uri)
            mExoPlayer?.setMediaItem(mediaItem)
            mExoPlayer?.prepare()
        }

        binding.loadNet.setOnClickListener {
            //加载网络资源
            val mp4Url = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
            val mediaItem: MediaItem = MediaItem.fromUri(mp4Url)
            mExoPlayer?.setMediaItem(mediaItem)
            mExoPlayer?.prepare()
        }

        //加载缓存资源
        binding.loadCache.setOnClickListener {
            val mp4Url = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
            val mediaItem: MediaItem = MediaItem.fromUri(mp4Url)
            val mHttpDataSourceFactory =
                DefaultHttpDataSource.Factory().setAllowCrossProtocolRedirects(true)
            val mCacheDataSourceFactory = CacheDataSource.Factory()
                .setCache(MyApp.cache)
                .setUpstreamDataSourceFactory(mHttpDataSourceFactory)
                .setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
            val source =
                ProgressiveMediaSource.Factory(mCacheDataSourceFactory).createMediaSource(mediaItem)
            mExoPlayer?.setMediaSource(source, true)
            mExoPlayer?.prepare()
        }

        //播放
        binding.play.setOnClickListener {
            //pause 后，可以直接调用 play()
            mExoPlayer?.play()
        }

        //暂停
        binding.pause.setOnClickListener {
            mExoPlayer?.pause()
        }

        //停止
        binding.stop.setOnClickListener {
            mExoPlayer?.stop()
        }

        //停止之后，更换资源
        binding.stopPrepare.setOnClickListener {
            //调用 stop 后。playbackState 为 STATE_IDLE
            //STATE_IDLE: 播放机处于空闲状态，必须做好准备才能播放媒体。
            if (mExoPlayer?.playbackState == Player.STATE_IDLE) {
                //设置资源是可选的
                val mediaItem: MediaItem =
                    MediaItem.fromUri("https://www.w3schools.com/html/movie.mp4")
                mExoPlayer?.setMediaItem(mediaItem)

                //stop 后，开始播放一定要调用 prepare()
                mExoPlayer?.prepare()
            }
        }

        //隐藏控制栏
        binding.hide.setOnClickListener {
            binding.playView.hideController()
        }

        //显示控制栏
        binding.show.setOnClickListener {
            binding.playView.showController()
        }

        //禁用控制器
        binding.remove.setOnClickListener {
            binding.playView.useController = false
        }

        //静音
        binding.nosound.setOnClickListener {
            mExoPlayer?.volume = 0f
        }

        //有声音
        binding.hassound.setOnClickListener {
            mExoPlayer?.volume = 1f
        }

        //页面销毁，释放资源，此后，不能再使用 player
        binding.release.setOnClickListener {
            mExoPlayer?.release()
        }

        //0.5倍速
        binding.speedHalf.setOnClickListener {
            mExoPlayer?.setPlaybackSpeed(0.5f)
        }

        //正常播放
        binding.speedNormal.setOnClickListener {
            mExoPlayer?.setPlaybackSpeed(1f)
        }

        //2倍速
        binding.speed2.setOnClickListener {
            mExoPlayer?.setPlaybackSpeed(2f)
        }

        //4倍速
        binding.speed4.setOnClickListener {
            mExoPlayer?.setPlaybackSpeed(4f)
        }
    }

    private fun initMp4() {
        mExoPlayer = SimpleExoPlayer.Builder(this)
            .build().apply {
                repeatMode = Player.REPEAT_MODE_ONE  //关闭循环播放
                volume = 0.5f
                addListener(mPlayerListener)
            }
    }

    private val mPlayerListener = object : Player.Listener {
        override fun onPlaybackStateChanged(state: Int) {
            super.onPlaybackStateChanged(state)
            when(state){
                Player.STATE_ENDED -> {
                    Log.d("zyj-", "播放结束")
                }
                Player.STATE_IDLE -> {
                    Log.d("zyj-", "播放器空闲")
                }
                Player.STATE_BUFFERING -> {
                    Log.d("zyj-", "播放器正在缓存，还没开始播放")
                }
                Player.STATE_READY -> {
                    //如果getPlayWhenReady（）为true，则播放器将正在播放，否则将暂停。
                    Log.d("zyj-", "播放器可以直接播放")
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mExoPlayer?.release()
    }
}